package com.ruoyi.web.controller.zkcontroller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.web.controller.common.BaseContext;
import com.ruoyi.web.domain.ShoppingCart;
import com.ruoyi.web.service.zkService.ShoppingCartService;
import com.ruoyi.web.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 向购物车中添加数据
     * @param shoppingCart
     * @param request
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpServletRequest request){
        log.info("接收到向购物车保存数据请求 添加数据{}",shoppingCart);
        Long UserId = BaseContext.getCurrentId();
        shoppingCart.setUserId(UserId);

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,UserId);

        //查询当前菜品是否在购物车中
        Long dishId = shoppingCart.getDishId();
        //如果不在那么将它添加到购物车
        if(dishId!=null){
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
        }

        //判断是否存在
        ShoppingCart one = shoppingCartService.getOne(queryWrapper);

        if(one!=null){
            //已经存在当前菜品数量增加
            int num = one.getNumber();
            one.setNumber(num+1);
            shoppingCartService.updateById(one);
        }else {
            //不存在，保存当前数据
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            one = shoppingCart;
        }
        return R.ok(one);
    }
}

